package vip.mtdp.asset.core.manager;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.mtdp.asset.api.dto.TxnDTO;
import vip.mtdp.asset.api.constants.TxnStateEnum;
import vip.mtdp.asset.core.dal.dao.TxnItemMapper;
import vip.mtdp.asset.core.dal.dao.TxnMapper;
import vip.mtdp.asset.core.dal.domain.Txn;
import vip.mtdp.asset.core.dal.domain.TxnItem;
import vip.mtdp.common.exception.AppRTException;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description
 * @Author Evans.wang
 * @since 2023/10/29 14:19
 **/
@Slf4j
@Service
public class TxnManager {

    @Autowired
    private TxnMapper txnMapper;

    @Autowired
    private TxnItemMapper txnItemMapper;


    /**
     * 创建交易
     * @param txnDTO
     * @return
     */
    @Transactional
    public TxnDTO create(TxnDTO txnDTO){
        Txn txn = new Txn();
        BeanUtil.copyProperties(txnDTO, txn);
        txn.setState(TxnStateEnum.INIT.getCode());
        int cnt = txnMapper.insert(txn);

        List<TxnDTO.TxnItemDTO> txnItemDTOList = txnDTO.getTxnItemDTOList();
        if (txnItemDTOList != null && !txnItemDTOList.isEmpty()){
            List<TxnItem> txnItemList = new ArrayList<>();
            txnItemDTOList.forEach(e -> {
                TxnItem txnItem = new TxnItem();
                BeanUtil.copyProperties(e, txnItem);
                txnItem.setTxnId(txn.getId());
                Date d = new Date();
                txnItem.setUpdateTime(d);
                txnItem.setCreateTime(d);
                txnItemList.add(txnItem);
            });
            int cntItem = txnItemMapper.batchInsert(txnItemList);
            if (cntItem != txnItemDTOList.size()){
                log.warn("create txn item fail. orderId = {}", txnDTO.getOrderId());
                throw new AppRTException("create txn fail");
            }
        }
        if (cnt != 1){
            throw new AppRTException("create txn fail");
        }
        txnDTO.setId(txn.getId());
        txnDTO.setState(txn.getState());
        return txnDTO;
    }

    /**
     * 更新交易状态
     * @param txnId
     * @param txnStateEnum
     * @return
     */
    public boolean updateTxnState(Long txnId, TxnStateEnum txnStateEnum){
        Txn txn = new Txn();
        txn.setId(txnId);
        txn.setState(txnStateEnum.getCode());
        return txnMapper.updateById(txn) == 1;
    }

}
